package pl.word.app.security;

import javax.inject.Inject;

import org.jboss.seam.security.Authenticator;
import org.jboss.seam.security.BaseAuthenticator;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.picketlink.idm.impl.api.PasswordCredential;
import org.picketlink.idm.impl.api.model.SimpleUser;

import pl.word.domain.model.User;
import pl.word.domain.service.UserService;

/**
 * Uwierzytelnianie i autoryzacja uyztkownika.
 * 
 * @author and.lachowski
 * 
 */
public class WordAuthenticator extends BaseAuthenticator implements
		Authenticator {

	@Inject
	private Credentials credentials;

	@Inject
	private Identity identity;

	@Inject
	private UserService userService;

	/**
	 * Metoda uruchamiana podczas uwierzytelniania.
	 */
	@Override
	public void authenticate() {

		// pobranie nazwy uzytkonika
		String username = credentials.getUsername();

		// pobranie uzytkonika o zadanym loginie z bazy danych
		User user = userService.getUserWithRoleByUsername(username);

		// sprawdzenie loginu i hasla uzytkonika
		if (user != null && checkUsername(user.getUsername())
				&& checkPassword(user.getPassword())) {

			// oznaczenie sukcesu
			setStatus(AuthenticationStatus.SUCCESS);

			// stworzeni uzytkonika w sesji z nadaniem uprawnień
			setUser(new SimpleUser(user.getUsername()));
			identity.addRole(user.getRole().getRoleName().name(),
					Restrictions.SECURITY_GROUP,
					Restrictions.SECURITY_GROUP_TYPE);

		} else {
			// oznaczenie porazki
			setStatus(AuthenticationStatus.FAILURE);
		}

	}

	/**
	 * Sprawdza poprawność hasła.
	 * 
	 * @param password
	 *            wpisane hasło
	 * @return
	 */
	private boolean checkPassword(String password) {

		if (credentials.getCredential() instanceof PasswordCredential) {
			return password.equals(((PasswordCredential) credentials
					.getCredential()).getValue());
		} else {
			return false;
		}
	}

	/**
	 * Sprawdza poprawność login.
	 * 
	 * @param username
	 *            wpisany login
	 * @return
	 */
	private boolean checkUsername(String username) {
		return username.equals(credentials.getUsername());
	}

}